package cc.idoone.joddhttp.servlet;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author hemj
 * @version 2017/8/1
 */
public class WebUtils {

    /**
     * 读取输入参数，转化为 HashMap 形式
     */
    public static Map<String, String> getParamMap(HttpServletRequest req) {
        Map<String, String> paramMap = new HashMap<String, String>();
        Enumeration<String> pns = req.getParameterNames();
        while (pns.hasMoreElements()) {
            String key = pns.nextElement();
            if (key != null) {
                String[] vals = req.getParameterValues(key);
                if (vals.length == 1) {
                    paramMap.put(key, vals[0]);
                } else {
                    StringBuffer val = new StringBuffer();
                    for (int i = 0; i < vals.length; i++) {
                        if (val.length() == 0) {
                            val.append(vals[i]);
                        } else {
                            val.append(",").append(vals[i]);
                        }
                    }
                    paramMap.put(key, val.toString());
                }
            }
        }
        return paramMap;
    }

    /**
     * 获取所有的请求消息头(比较重要的有：host,user-agent,referer,accept-language)
     */
    public static Map<String, String> getHeaderMap(HttpServletRequest req) {
        Map<String, String> headerMap = new HashMap<String, String>();
        Enumeration<String> pns = req.getHeaderNames();
        while (pns.hasMoreElements()) {
            String headerName = pns.nextElement();
            Enumeration<String> headerValues = req.getHeaders(headerName);
            StringBuffer val = new StringBuffer();
            while (headerValues.hasMoreElements()) {
                if (val.length() > 0) {
                    val.append(",");
                }
                val.append(headerValues.nextElement());
            }
            headerMap.put(headerName.replace('-', '_'), val.toString());
        }
        return headerMap;
    }
}
